package com.jp.refreshlocalcacheclient.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @Author: jipeng
 * @Description: 应用上下文工具
 * @Date: Created in 2020/5/14 19:44
 */
@Component
public class ApplicationContextUtil implements ApplicationContextAware, DisposableBean {
    private static Logger logger = LoggerFactory.getLogger(ApplicationContextUtil.class);

    private static ApplicationContext applicationContext;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(ApplicationContextUtil.applicationContext == null){
            logger.info("ApplicationContextUtil.applicationContext init");
        }else{
            logger.warn("ApplicationContextUtil.applicationContext override");
        }

        ApplicationContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }


    @Override
    public void destroy() throws Exception {
        applicationContext = null;
    }


    public static <T> T getBean(String name){
        check();
        return (T)applicationContext.getBean(name);
    }

    public static <T> T getBean(Class<T> var1){
        check();
        return (T)applicationContext.getBean(var1);
    }


    private static void check() {
        if (applicationContext == null) {
            throw new NullPointerException("not has applicationContext");
        }
    }
}
